<?php
/**
 * Zhub - A PHP Framework For API Developer
 *
 * This file is part of the Zhub package.
 *
 * (c) YiLong Fan <fantiq@163.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author fanyilong <fantiq@163.com>
 * @copyright 2017 fanyilong. All rights reserved.
 * @package Zhub
 * @date 18-3-1
 */

namespace Zhub\Console;


use Zhub\Console\Exceptions\CommandNotFoundException;
use Zhub\Console\Exceptions\MissingCommandException;

class ConsoleKernel
{
    private $arguments = [];

    private $command = null;

    public $rootPath = null;

    public $rootNameSpace = null;

    private static $commands = [];

    public function __construct(array $arguments, string $rootPath, string $rootNameSpace = '')
    {
        $this->rootPath = $rootPath;
        $this->rootNameSpace = $rootNameSpace;
        $this->arguments = $arguments;
        $this->command = array_shift($this->arguments);
        if (empty($this->command)) {
            throw new MissingCommandException();
        }
    }

    public function run()
    {
        if (!array_key_exists($this->command, self::$commands)) {
            throw new CommandNotFoundException($this->command);
        }
        $command = self::$commands[$this->command];
        return call_user_func([$command, 'run'], $this);
    }

    public function registry(Command ...$commands)
    {
        foreach ($commands as $command) {
            $name = $command->name();
            if (empty($name)) {
                // missing command
            }
            if (!array_key_exists($name, self::$commands)) {
                self::$commands[$name] = $command;
            }
        }
    }

    public function getCommand():string
    {
        return $this->command;
    }

    public function getArguments():array
    {
        return $this->arguments;
    }

    public function getCommands():array
    {
        return self::$commands;
    }
}
